package thread.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liweimin
 * @date 2021/5/7 11:42
 * @since
 */
public class Test02 {
    public static void main(String[] args) throws InterruptedException {
        SubThread subThread = new SubThread();
        new Thread(subThread::method).start();
        Thread.sleep(50);
        Thread thread = new Thread(subThread::method);
        thread.start();
        Thread.sleep(50);
        thread.interrupt();//只是修改flag值


    }

    static class SubThread {
        private Lock lock = new ReentrantLock();

        public void method() {
            try {
//                lock.lock();//获得锁，即使调用线程的interrupt方法 也没有中断线程
                lock.lockInterruptibly();//线程未被中断获得锁，反之则不获得锁
                System.out.println(Thread.currentThread().getName() + "==>begin lock");

                for (int i = 0; i < Integer.MAX_VALUE; i++) {
                    new StringBuilder();
                }
                System.out.println(Thread.currentThread().getName() + "==>end lock");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();//释放锁
                System.out.println(Thread.currentThread().getName() + "==释放锁");
            }

        }
    }
}
